import Vue from 'vue'
import Router from 'vue-router'
import store from './../store'

import entrance from '@/components/entrance/main'
import signUp from '@/components/entrance/signUp'
import signIn from '@/components/entrance/signIn'

import home from '@/components/home/main'
import desktop from '@/components/home/desktop'
import village from '@/components/home/village'

import notFound from '@/components/notFound'

Vue.use(Router)

var router = new Router({
    //开启此模式需要注意vue-resource的异步请求都要以 / 开头,表明请求路径拼接到url根路径后,否则会造成url多余的请求
    //举例: 访问登录页面的url为:http://localhost:8080/entrance/sign_in,那么当在登录页面发起请求: api/login,
    //因为不加 / ,所以最后发起的请求路径为: http://localhost:8080/entrance/api/login,这显然是不对的,加上 / 后,
    //请求路径为: http://localhost:8080/api/login,这才是正确的
    //另外需要提醒的是,如果没有使用history模式,那么加不加 / 都无所谓,因为都是相对于url跟路径
    mode: 'history',
    routes: [
        {
            path: '/',
            redirect : '/entrance/sign_in'
        },
        {
            path: '/entrance',
            redirect : '/entrance/sign_in',
            component: entrance,
            children : [
                //{ path: '/', components: {'default': header,'left': leftBox,'main': mainBox}
                //{ path: '', component : signIn },
                { path: 'sign_up', component : signUp ,name : 'sign_up'},
                { path: 'sign_in', component : signIn ,name : 'sign_in'}
            ]
        },
        {
            path : '/home',
            redirect : '/home/desktop',
            component : home,
            //meta: {
            //    requireAuth: true  // 添加该字段，表示进入这个路由是需要登录的
            //},
            name : 'home',
            children : [
                { path : 'desktop', component : desktop, name : 'desktop',meta: { requireAuth: true } },
                { path : 'village', component : village, name : 'village',meta: { requireAuth: true } }
            ]
        },
        {
            path : '/notFound',
            component : notFound
        }
    ]
    //linkActiveClass: 'mui-active' // 覆盖默认的路由高亮的类，默认的类叫做 router-link-active
})

router.beforeEach((to, from, next) => {
    if(to.matched.length === 0)
        //跳转404页面
        return next({ path : '/notFound'})
    //检测该路由是否需要校验
    if(to.meta.requireAuth === true){
        //使用vuex和localStore缓存认证信息的手段并不安全
        //发送异步请求
        Vue.http.get('/api/auth/enterHome',{})
            .then((res) => {
                var result = res.data
                if(result.status === 1) return next({ path : '/entrance/sign_in'})
                next()
            },(err) => {
                return next({ path : '/entrance/sign_in'})
            })
    }
    next()
})
export default router
